package com.doge.walknovel.business.search

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.core.view.setPadding
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.doge.wnpro.R
import com.doge.walknovel.analysis.analysisEvent
import com.doge.walknovel.analysis.search_result_clicked
import com.doge.walknovel.api.model.NovelInfo
import com.doge.walknovel.business.novel.NovelDetailActivity
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.core.BaseActivity
import com.doge.walknovel.core.base.adapters.ITEM_CLICKED
import com.doge.walknovel.core.base.isRefreshing
import com.doge.wnpro.databinding.ActivitySearchBinding
import com.doge.walknovel.utils.closeKeyBoard
import com.doge.walknovel.utils.setOnClickCallback
import com.doge.walknovel.utils.systemWindowInsetsTop
import com.doge.walknovel.utils.toast

class SearchActivity : BaseActivity() {
    private val binding by lazy { ActivitySearchBinding.inflate(layoutInflater) }

    private val viewModel: SearchViewModel by viewModels { SearchViewModelFactory() }
    private val adapter by lazy { SearchAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        SearchHistoryHelper.initialized()
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }
        binding.back.setOnClickCallback { onBackPressed() }
        binding.confirm.setOnClickCallback { search() }
        binding.layHistory.setListener(object : SearchHistoryLayout.Callback {
            override fun onKeyClicked(key: String) {
                binding.search.setText(key)
                binding.search.setSelection(key.length)
                search()
            }
        })
        binding.searchDelete.setOnClickCallback {
            binding.search.setText("")
        }
        binding.search.addTextChangedListener(onTextChanged = { s, _, _, _ ->
            binding.searchDelete.visibility =
                if (s?.isNotEmpty() == true) View.VISIBLE else View.GONE
            if (s.isNullOrEmpty()) {
                binding.layHistory.visibility = View.VISIBLE
                viewModel.searchClear()
            }
        })
        binding.recyclerView.itemAnimator = null
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        binding.refreshLayout.setColorSchemeResources(R.color.pull_refresh)
        binding.refreshLayout.setOnRefreshListener {
            search()
        }
        SearchHistoryHelper.currentHistoryKeys.observe(this) {
            binding.layHistory.set(it)
        }
        viewModel.loading.observe(this) {
            binding.refreshLayout.isRefreshing = it.isRefreshing()
        }
        viewModel.dataList.observe(this) {
            adapter.submitList(it)
        }
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> {
                analysisEvent(search_result_clicked)
                NovelDetailActivity.start(this, (item as? NovelInfo?)?.novelId, NovelRefer.search)
            }
        }
    }

    private fun search() {
        closeKeyBoard()
        val input = binding.search.text.toString()
        if (input.isEmpty()) {
            toast(R.string.search_what_you_want)
            binding.refreshLayout.isRefreshing = false
        } else {
            SearchHistoryHelper.recordNewKey(input)
            viewModel.request(input)
            binding.layHistory.visibility = View.GONE
        }
    }

    companion object {
        fun start(context: Context) {
            context.startActivity(Intent(context, SearchActivity::class.java))
        }
    }
}